#include "protocol.h"
#include "set_sok.h"
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define PORT 8016
#define SERVER_IPV6 "::1" // IPv6 本地回环地址
#define TRY_TIMEOUT 4
#define WAIT_SEC 0
#define WAIT_USEC 100000
int send_to_pmc1(char const *addr6, const uint16_t port, char const *msg) {
	int sock = 0;
	struct sockaddr_in6 serv_addr;

	// 创建 socket
	if ((sock = socket(AF_INET6, SOCK_STREAM, 0)) < 0) {
		perror("socket creation failed");
		exit(EXIT_FAILURE);
	}

	if (set_block_timout(sock, WAIT_SEC, WAIT_USEC)) {
		exit(EXIT_FAILURE);
	}
	
	serv_addr.sin6_family = AF_INET6;
	serv_addr.sin6_port = htons(port);

	// 转换 IPv4 和 IPv6 地址从文本到二进制形式
	if (inet_pton(AF_INET6, addr6, &serv_addr.sin6_addr) <= 0) {
		perror("invalid address / address not supported");
		exit(EXIT_FAILURE);
	}


	// 连接到服务器，
	if ( connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0 ) {
		//perror("");
		return -1;
	}

	// 发送消息
	qs_send(sock, msg);

	// 读取响应
	char *ret = qs_recv(sock, QSONT_MAX_LEN);
	printf("%s", ret);
	free(ret);

	close(sock);
	return 0;
}

int main(int argc, char **argv) {
	if (argc != 2) {
		fprintf(stderr, "must type ONE param.\n");
		exit(1);
	}

	// 尝试一定次数
	// 重新创建套接字以规避某些风险
	int count = 0;
	while ( count < TRY_TIMEOUT) {
		count++;
		if (!send_to_pmc1(SERVER_IPV6, PORT, argv[1])) {
			return 0;
		}
	}

	fprintf(stderr, "Failed to send.\n");
	return 1;
}

